<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const items = [
        {
          id: '604e21feb205b95968e13129',
          pid: '0',
          name: '总裁办',
        },
        {
          id: '604e223fb205b95968e1312b',
          pid: '0',
          name: '人事部',
        },
        {
          id: '604e2251b205b95968e1312c',
          pid: '0',
          name: '财务部',
        },
        {
          id: '604e2262b205b95968e1312d',
          pid: '604e2251b205b95968e1312c',
          name: '财务核算部',
        },
        {
          id: '604e227db205b95968e1312e',
          pid: '604e2251b205b95968e1312c',
          name: '税务管理部',
        },
        {
          id: '604e2297b205b95968e1312f',
          pid: '604e2251b205b95968e1312c',
          name: '薪资管理部',
        },
        {
          id: '6051ad90e93db6522c1d00d2',
          pid: '0',
          name: '技术部',
        },
        {
          id: '6051adb6e93db6522c1d00d3',
          pid: '6051ad90e93db6522c1d00d2',
          name: 'Java研发部',
        },
        {
          id: '6051add6e93db6522c1d00d4',
          pid: '6051ad90e93db6522c1d00d2',
          name: 'Python研发部',
        },
        {
          id: '6051adefe93db6522c1d00d5',
          pid: '6051ad90e93db6522c1d00d2',
          name: 'Php研发部',
        },
      ]
      function ToTree(items) {
        //新建数组
        const newArr = []
        const arr = []
        for (let i = 0; i < items.length; i++) {
          let obj = {}
          obj = items[i]
          newArr.push(obj)
        }
        // pid是0的新建下级部门
        for (let i = 0; i < newArr.length; i++) {
          if (newArr[i].pid === '0') {
            newArr[i].children = []
          }
        }
        //将下级部门添加到children
        for (let i = 0; i < newArr.length; i++) {
          for (let j = 0; j < newArr.length; j++) {
            if (newArr[j].pid === newArr[i].id) {
              newArr[i].children.push(newArr[j])
            }
          }
        }
        //pid不为0的数组加入arr
        for (let i = 0; i < newArr.length; i++) {
          if (newArr[i].pid === '0') {
            arr.push(newArr[i])
          }
        }
        // console.log(arr[2].children)
        // console.log(arr[3].children)
        return arr
      }
      console.log(ToTree(items))
    </script>
  </body>
</html>
